package com.flink.examples.window;

import com.flink.examples.DataSource;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.util.List;

/**
 * @Description sessionWindows会话窗口：按不活跃时间切成不同分区窗口，并进行窗口计算
 * @Author JL
 * @Date 2020/09/15
 * @Version V1.0
 */
public class SessionWindow {

    /**
     * 遍历集合，返回会话滑动窗口下按不活跃时间切分后的，每个窗口下性别分区里最大年龄数据记录
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置流处理时间事件,对于会话窗口必需设置此时间类型，有三种类型:
        //1.ProcessingTime：以operator处理的时间为准，它使用的是机器的系统时间来作为data stream的时间
        //2.IngestionTime：以数据进入flink streaming data flow的时间为准
        //3.EventTime：以数据自带的时间戳字段为准，应用程序需要指定如何从record中抽取时间戳字段
        env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime);
        env.setParallelism(4);
        DataStream<Tuple3<String, String, Integer>> inStream = env.addSource(new MyRichSourceFunction());
        DataStream<Tuple3<String, String, Integer>> dataStream = inStream.keyBy((KeySelector<Tuple3<String, String, Integer>, String>) k ->k.f1)
                //按会话窗口滚动，当2秒之内没有指定分区数据流，则计算一次
                //会话窗口是根据在指定时间之后没有活跃的数据接入,则认为窗口结束，进行窗口计算
                .window(EventTimeSessionWindows.withGap(Time.seconds(2)))
                .reduce(new ReduceFunction<Tuple3<String, String, Integer>>() {
                    @Override
                    public Tuple3<String, String, Integer> reduce(Tuple3<String, String, Integer> t1, Tuple3<String, String, Integer> t2) throws Exception {
                        //返回年龄最大的
                        return t1.f2 > t2.f2 ? t1: t2;
                    }
                });
        dataStream.print();
        env.execute("flink EventTimeSessionWindows job");
    }

    /**
     * 模拟数据持续输出
     */
    public static class MyRichSourceFunction extends RichParallelSourceFunction<Tuple3<String, String, Integer>> {
        @Override
        public void run(SourceContext<Tuple3<String, String, Integer>> ctx) throws Exception {
            List<Tuple3<String, String, Integer>> tuple3List = DataSource.getTuple3ToList();
            for (Tuple3 tuple3 : tuple3List){
                ctx.collect(tuple3);
                //1秒钟输出一个
                Thread.sleep(2 * 1000);
            }
        }
        @Override
        public void cancel() {
            try{
                super.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
/*
2> (张三,man,20)
4> (李四,girl,24)
2> (王五,man,29)
4> (刘六,girl,32)
2> (吴八,man,30)
*/
